package com.javaweb.servlet.action;

import com.javaweb.servlet.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        /*获取表单数据*/
        String name = request.getParameter("name");
        String password01 = request.getParameter("password01");
        String password02 = request.getParameter("password02");
        if(!password01.equals(password02)){
            request.setAttribute("pwdmsg","两次密码不一致!");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
        /*链接数据库*/
        Connection conn=null;
        PreparedStatement ps =null;
        int count=0;
        try {
            /*获取链接*/
            conn = DBUtil.getConnection();
            /*获取预编译的数据库操作对象*/
            String sql ="insert into t_student(account,password) value (?,?)";
            ps=conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setString(2,password01);
            /*执行Sql语句*/
            count=ps.executeUpdate();
            /*处理结果集*/

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                /*释放资源*/
                DBUtil.close(conn,ps,null);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (count==1) {
/*            这地方需要注意一下这个一个表单传过来的数据这是一个post请求，所以你转发的页面要有
                    doPost()方法*/
/*            request.getRequestDispatcher("/dept/list").forward(request,response);*/
            /*这里最好使用重定向(浏览器会发送一次全新的请求)
            浏览器在地址栏上发送请求，这个请求是get请求 这样doPost方法就可以不用写了 */
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else{
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }
    }
}
